import BoxUtil from "@/assets/js/utils/BoxUtil";
import Measure from '@/components/map/measure';
import SmQuery from '@/assets/js/utils/SmQuery';
import Binder from '@/utils/binder';
import Svg2Png from '@/utils/svg2png';
import '@/assets/mapbox/libs/draw/mapbox-gl-draw.css'
import MapBoxDraw from '@/assets/mapbox/libs/draw/mapbox-gl-draw.js'
import popWin from "@/pages/yzt/components/popWin"; // 属性弹出框

import LotsOfPointsMode from '@/assets/js/plot/test.js'
import Rectangle from '@/assets/js/plot/Rectangle.js'
import freePolygon from 'mapbox-gl-draw-freehand-mode'
import DrawStraightArrow from '@/assets/js/plot/StraightArrow.js'
import DrawDiagonalArrow from '@/assets/js/plot/DiagonalArrow.js'
import DrawDoveTailStraightArrow from '@/assets/js/plot/DoveTailStraightArrow.js'
import DrawDoveTailDiagonalArrow from '@/assets/js/plot/DoveTailDiagonalArrow.js'
import DrawDoubleArrow from '@/assets/js/plot/DoubleArrow.js'
import { add, remove, update } from '@/api/xcgl/ysbj'

import Vue from "vue";
import store from '@/store'
export default class MapService {

  /**
   *  构造函数
   * @param mapBox HgcMapBoxUtil
   */
  constructor(mapBox, sf) {
    this.hgcMapBoxUtil = mapBox; //地图操作基础类
    this.isMapInitComplete = false; //地图style初始化是否完成
    this.baseMapLayers = []; //当前显示的底图数组
    this.topCanvasLayers = []; //顶部不动的图层（标绘图层）
    this.getMap().on('style.load', this._mapStyleLoadComplete.bind(this)); //地图初始化
    this.mapDataEvent = {}; //地图数据加载事件
    this.tempMarker = new mapboxgl.Marker();
    this._m = new Measure(mapBox);
    this.binder = new Binder();
    this._svg = new Svg2Png();
    this._drawControl = undefined;

    this.drawControlStyles = [
      {
        'id': 'points-symbol-normal',
        'type': 'symbol',
        'filter': ['all',
          ['==', '$type', 'Point'],
          ['==', 'meta', 'feature']
        ],
        'layout': {
          'icon-image': '{user_uid}'
        }
      },
      {
        'id': 'highlight-active-points',
        'type': 'circle',
        'filter': ['all',
          ['==', '$type', 'Point'],
          ['==', 'meta', 'feature'],
          ['==', 'active', 'true']
        ],
        'paint': {
          'circle-radius': 5,
          'circle-color': '#ff000f'
        }
      },
      // {
      //   'id': 'points-normal',
      //   'type': 'circle',
      //   'filter': ['all',
      //     ['==', '$type', 'Point'],
      //     ['==', 'meta', 'feature'],
      //     ['==', 'active', 'false']],
      //   'paint': {
      //     'circle-radius': 5,
      //     'circle-color': '#ff0000'
      //   }
      // },

      //线Active
      {
        "id": "gl-draw-line-active",
        "type": "line",
        "filter": ["all", ["==", "$type", "LineString"],
          ['==', 'active', 'true']
        ],
        "layout": {
          "line-cap": "round",
          "line-join": "round"
        },
        "paint": {
          "line-color": "#D20C0C",
          "line-dasharray": [0.2, 2],
          "line-width": 2
        }
      },
      //面Active
      {
        "id": "gl-draw-polygon-fill-active",
        "type": "fill",
        "filter": ["all", ["==", "$type", "Polygon"],
          ['==', 'active', 'true']
        ],
        "paint": {
          "fill-color": "#618a31",
          "fill-outline-color": "#D20C0C",
          "fill-opacity": 0.5
        }
      },
      {
        "id": "gl-draw-polygon-stroke-active",
        "type": "line",
        "filter": ["all", ["==", "$type", "Polygon"],
          ['==', 'active', 'true']
        ],
        "layout": {
          "line-cap": "round",
          "line-join": "round"
        },
        "paint": {
          "line-color": "#000000",
          "line-dasharray": [0.2, 2],
          "line-width": 2
        }
      },
      //节点vertex points
      {
        "id": "gl-draw-polygon-and-line-vertex-halo-active",
        "type": "circle",
        "filter": ["all", ["==", "meta", "vertex"],
          ["==", "$type", "Point"],
          ["!=", "mode", "static"]
        ],
        "paint": {
          "circle-radius": 6,
          "circle-color": "#FFF"
        }
      },
      {
        "id": "gl-draw-polygon-and-line-vertex-active",
        "type": "circle",
        "filter": ["all", ["==", "meta", "vertex"],
          ["==", "$type", "Point"],
          ["!=", "mode", "static"]
        ],
        "paint": {
          "circle-radius": 5,
          "circle-color": "#D20C0C",
        }
      }
    ];

    this.selectSymbol = undefined;
    this.drawControlCreate = this.drawControlCreate.bind(this);
    this.drawControlUpdate = this.drawControlUpdate.bind(this);
    this.drawControlDelete = this.drawControlDelete.bind(this);
    this.drawControlClick = this.drawControlClick.bind(this);
    this._drawControlModeChange = this._drawControlModeChange.bind(this);
    this.bindDrawControlEvent();
    this._remoteImages = [];
    this.popVue = new Vue({ store,render: h => h(popWin) });
    this.pop = new mapboxgl.Popup({
      closeOnClick: false, closeButton: true
    }).setDOMContent(this.popVue.$mount().$el);

    this.sf = sf;

    this._mouseClickEvent = this._mouseClickEvent.bind(this)
    this.hgcMapBoxUtil.getSortFactory().setOnMapClickListener(this._mouseClickEvent);
  }

  //添加超图封装的接口
  addSuperMapLayer(id, data) {
    this.hgcMapBoxUtil.getSortFactory().addGeoJsonLayer(id, data);
  }


  /**
   * 获取PopWin实例
   */
  getPop() {
    return this.pop;
  }


  
  /**
   * 获取PopWin组件
   */
  openPop(fc, attribute, lnglat) {
    this.popVue.$children[0].setTemplate(fc, attribute);
    this.pop.setLngLat(lnglat).addTo(this.getMap());
  }

  /**
   * 绑定事件
   * @param event
   * @param fn
   */
  on(event, fn, context) {
    if (typeof fn !== 'function') {
      console.error('第二个参数不是方法');
      return;
    }
    if (this.mapDataEvent[event] && Array.isArray(this.mapDataEvent[event])) {
      this.mapDataEvent[event].push(context ? fn.bind(context) : fn);
    } else {
      this.mapDataEvent[event] = [context ? fn.bind(context) : fn];
    }
  }

  /**
   * 解绑事件
   * @param event
   * @param fn
   */
  off(event, fn) {
    if (typeof fn !== 'function') {
      console.error('第二个参数不是方法');
      return;
    }
    if (this.mapDataEvent[event] && Array.isArray(this.mapDataEvent[event])) {
      this.mapDataEvent[event].splice(this.mapDataEvent[event].indexOf(fn), 1);
    } else {
      this.mapDataEvent[event] = [];
    }
  }


  /**
   * 绑定标绘控件事件
   */
  bindDrawControlEvent() {
    this.getMap().on('draw.create', this.drawControlCreate)
    this.getMap().on('draw.update', this.drawControlUpdate)
    this.getMap().on('draw.delete', this.drawControlDelete)
    this.getMap().on('draw.modechange', this._drawControlModeChange);
    this.getMap().on('click', this.drawControlClick)
  }

  // drawControlCreate(e) {
  //   const uid = this.selectSymbol ? this.selectSymbol._id : undefined;
  //   this._drawControl.setFeatureProperty(e.features[0].id, 'uid', uid);
  //   const param = e.features[0];
  //   param.properties = {
  //     uid: uid
  //   }
  //   this._triggerMouseEvent('map.create', e, this._drawControl);
  // }

  // drawControlUpdate(e) {
  //   const param = e.features[0];
  //   this._triggerMouseEvent('map.update', e, this._drawControl);
  // }

  // drawControlDelete(e) {
  //   const ids = e.features.map(o => o.id);
  //   this._triggerMouseEvent('map.delete', e, this._drawControl);
  // }


  /**
 * 绘制添加
 * @param e
 */
  drawControlCreate(e) {

    const uid = this.selectSymbol ? this.selectSymbol._id : undefined;
    this._drawControl.setFeatureProperty(e.features[0].id, 'uid', uid);
    const param = e.features[0];
    param.uid = store.getters.id;
    param.properties = { uid: uid }
    param.taskId = store.state.xcgl.selectTask._id;
    param.dept = store.getters.dept;
    param.status = 0;
    add(param).then(res => {
      this._triggerMouseEvent('map.create', e, this._drawControl);
    })

  }

  /**
   * 绘制更新
   * @param e
   */
  drawControlUpdate(e) {
    const param = e.features[0];
    update(param).then(res => {
      this._triggerMouseEvent('map.update', e, this._drawControl);
    })

  }

  /**
   * 绘制删除
   * @param e
   */
  drawControlDelete(e) {
    const ids = e.features.map(o => o.id);
    remove({ ids: ids }).then(res => {
      this._triggerMouseEvent('map.delete', e, this._drawControl);
    })
  }

  /**
     * 触发
     * @param e
     * @private
     */
  _fireDrawControlDelete(e) {
    const ids = e.features.map(o => o.id);
    this._drawControl.delete(ids);
    this.drawControlDelete(e);
    //this.map.fire("draw.delete")
  }


  
  drawControlClick(e) {
    if(this._drawControl){
      const fc =  this._drawControl.getSelected();
      this._triggerMouseEvent('map.draw.click',fc.features.length > 0 ? fc.features[0]:undefined)
    }
  
  }

  _drawControlModeChange(e) {
    this._triggerMouseEvent('map.modechange', e);
  }

  /**
   * 地图Style加载完成事件
   * @private
   */
  _mapStyleLoadComplete() {
    this.isMapInitComplete = true;
    this._triggerMouseEvent('map.init', this.getMap());
  }

  setDrawControlHighLight(type, ids) {
    this._drawControl.changeMode(type, ids);
  }



  /**
   * 鼠标事件触发器
   * @param evt
   * @private
   */
  _triggerMouseEvent(evt, e, id) {
    let ev = this.mapDataEvent[evt];
    let size = ev ? ev.length : 0;
    for (let i = 0; i < size; i++) {
      this.mapDataEvent[evt][i].call(this, e, id);
    }
  }

  /**
   * 获取地图
   * @returns {*}
   */
  getMap() {
    return this.hgcMapBoxUtil.getMap();
  }

  /**
   * 获取测量工具
   * @returns {Measure}
   */
  getMeasureTool() {
    return this._m;
  }

  /**
   * 地图操作类
   * @returns {*}
   */
  getHgcMapBoxUtil() {
    return this.hgcMapBoxUtil;
  }

  /**
   * 解析图层url
   * @param url
   * @private
   */
  _parseLayerUrl(url) {
    if (url) {
      this._parseLayerUrlParam(url);
      const urlArray = url.split('?');
      const realUrl = url.replace(urlArray[urlArray.length - 1], '');
      return realUrl.substring(0, realUrl.length - 1);
    }
    return url
  }

  /**
   * 解析图层查询数据
   * @param url
   * @returns {*}
   * @private
   */
  _parseLayerQueryUrl(url) {
    const real = this._parseLayerUrl(url);
    if (real.indexOf('/tileFeature') === -1) {
      return real;
    } else {
      return real.substring(0, real.indexOf('/tileFeature'));
    }
  }

  /**
   * 解析图层url参数
   * @param url
   * @private
   */
  _parseLayerUrlParam(url) {
    if (url) {
      const urlArray = url.split('?');
      try {
        var obj = JSON.parse(
          '{"' +
          decodeURIComponent(urlArray[urlArray.length - 1])
            .replace(/"/g, '\\"')
            .replace(/&/g, '","')
            .replace(/=/g, '":"') +
          '"}'
        )
      } catch (e) {
        console.warn("图层URL参数配置不正确，不能正常解析的JSON");
        return {};
      }
      return obj;
    }

  }

  /**
   *  添加图层
   * @param type
   * @param id    layerId的真实身份是sourceId
   * @param url
   * @param minZoom
   * @param maxZoom
   * @param beforeID
   * @returns {*}
   */
  addLayer(layer) {
    const realUrl = this._parseLayerUrl(layer.url);
    const param = this._parseLayerUrlParam(layer.url); //layerType,searchLayer

    try {
      if (!param || !param.layerType) {
        console.warn("名称为：\"" + layer.name + "\"的图层未配置图层类型!")
        return;
      }
      switch (param.layerType.trim()) {
        case "layer_sm_vec": //超图发布的矢量瓦片服务
          this.hgcMapBoxUtil.addVectorTileLayer(layer._id, realUrl, layer.minZoom, layer.maxZoom, true);
          break;
        case "layer_sm_map": //栅格瓦片服务
          this.hgcMapBoxUtil.addGridTileLayer(layer._id, realUrl, layer.minZoom, layer.maxZoom);
          break;
        case "layer_sm_25d": //2.5D服务
          this.hgcMapBoxUtil.addFillExtrusionLayer(layer._id, realUrl, layer.minZoom, layer.maxZoom);
          break;
        case 'layer_tdt_map': //天地图栅格瓦片服务
          this.hgcMapBoxUtil.addTdtGridTileLayer(layer._id, realUrl, layer.minZoom, layer.maxZoom,layer.bounds);
          break;
        case 'layer_sm_es': //EChart服务
          this.hgcMapBoxUtil.addEchartsLayer(layer.url);
          break;
        case 'layer_hgc_geojson': //接入自定义服务 {query:"/甘南县/",queryField:"properties.district"}
          this.hgcMapBoxUtil.addHgcCustomLayer(layer._id, realUrl, layer.minZoom, layer.maxZoom, true,undefined); //添加filter
          break;
        default:
          break;

      }
    } catch (e) {
      console.warn(e)
    }


  }



  /**
   * 设置图层开关
   *
   * 先对图层添加和删除，再对高亮图层的添加和删除
   * 再绑定图层的属性查询事件
   */
  setLayerVisible(isVisible, layer) {
    if (!isVisible) {
      this.removeLayer(layer._id);
    } else {
      this.addLayer(layer)
    }
  }



  //  鼠标点击事件
  _mouseClickEvent(type, e) {

    switch (type) {
      case "enter":
        break;
      case "leave":
        break;
      case "click":
        this._triggerMouseEvent('map.click', e)
        break;
    }

  }


  /**
   * 设置图层透明度
   * @param value
   * @param sourceId 数据源ID
   */
  setOpacityValue(value, layer) {
    this.hgcMapBoxUtil.setLayerOpacity(layer._id, value);
  }


  addTempLayer(layer){
    //注册
    this.sf.addSortLayer(layer._id,31,layer.name,layer);
    this.addLayer(layer);

  }

  /**
   * 移除瓦片
   * @param soureId 数据源ID
   */
  removeLayer(sourceId) {
    this.hgcMapBoxUtil.removeTileLayer(sourceId);
  }




 
  //临时图层删除
  removeTempLayer(sourceId){
    this.removeLayer(sourceId);
    this.sf.removeSortLayer(sourceId);
  }




  /**
   * 切换底图
   * @param layerGroup
   */
  async addBaseLayer(layerGroup) {
    if (!Array.isArray(layerGroup)) {
      throw ('layerGroup 不是个数组，检查数据！');
    }
    //移除
    this.baseMapLayers.forEach(layer => {
      this.removeLayer(layer._id);
    });
    this.baseMapLayers = [];
    //添加图层到地图
    for (let i = 0; i < layerGroup.length; i++) {
      const layer = layerGroup[i];
      await this.addLayer(layer);
    }

    this.baseMapLayers = layerGroup;
  }

  /**
   * 通过图层边界设置地图边界
   * @param layer
   */
  async setMapBoundsByLayerBounds(layer) {

    let source = this.getMap().getSource(layer._id);
    if (source && source.bounds) {
      this.getMap().fitBounds([
        [source.bounds[2], source.bounds[3]],
        [source.bounds[0], source.bounds[1]]
      ], {
        padding: 20
      });
    } else {
      const realUrl = this._parseLayerUrl(layer.url);
      const res = await this.hgcMapBoxUtil.getBoundfromServer(realUrl + '.json');
      this.getMap().fitBounds([
        [res.data.bounds.left, res.data.bounds.bottom],
        [res.data.bounds.right, res.data.bounds.top]
      ], {
        padding: 20
      });
    }

  }




  /**
   * 加载系统符号库的点图片
   * @param s
   * @private
   */
  _loadPointImage(s) {
    const image = this._svg.getCanvasImageData(s.flag, {
      strokeStyle: s.strokeStyle,
      fillStyle: s.fillStyle,
      lineWidth: s.lineWidth
    });
    this.hgcMapBoxUtil.addPng(s._id, image);
  }



  /**
  * 定位Geometry
  * @param geometry
  */
  flyTo(geometry, zoom) {

    switch (geometry.type) {
      case 'Point':
        this.getMap().flyTo({ center: geometry.coordinates, zoom: zoom || 13 })
        break
      case 'LineString':
        var bounds = BoxUtil.getCoordinatesBounds(geometry.coordinates)
        this.getMap().fitBounds(bounds, { padding: 50 })
        break
      case 'Polygon': // 闭合
        var bounds = BoxUtil.getCoordinatesBounds(geometry.coordinates[0])
        this.getMap().fitBounds(bounds, { padding: 50 })
        break
    }
  }


  /**
   * 给Map加载符号库
   * @param symbols
   */
  addloadSymbols(symbols) {
    if (!Array.isArray(symbols)) {
      return;
    }
    symbols.forEach(symbol => {
      this.hgcMapBoxUtil.addImage(symbol.symbolName, symbol.symbolPath);
    });
  }


  /**
   * 创建DrawControl
   * @param symbols
   * @returns {MapBoxDraw|*}
   */
  createDrawControl(symbols) {
    if (this._drawControl) {
      this.getMap().removeControl(this._drawControl);
    }
    let layers = []
    symbols.forEach(s => {
      switch (s.type) {
        case 0:
          this._loadPointImage(s);
          break;
        case 1:
          layers.push({
            "id": s._id,
            "type": "line",
            "filter": ["all", ["==", "$type", "LineString"],
              ['==', 'active', 'false'],
              ['==', 'user_uid', s._id]
            ],
            "layout": {
              "line-cap": "round",
              "line-join": "round"
            },
            "paint": {
              "line-color": s.strokeStyle || "#000",
              "line-width": s.lineWidth / 50 || 3
            }
          });
          break;
        case 2:
          layers.push({
            "id": s._id,
            "type": "fill",
            "filter": ["all", ["==", "$type", "Polygon"],
              ['==', 'active', 'false'],
              ['==', 'user_uid', s._id]
            ],
            "paint": {
              "fill-color": s.fillStyle || "rgba(0,0,0,0)",
              "fill-outline-color": s.strokeStyle || "#000",
            }
          })
          layers.push({
            "id": s._id + "-stroke-line",
            "type": "line",
            "filter": ["all", ["==", "$type", "Polygon"],
              ['==', 'active', 'false'],
              ['==', 'user_uid', s._id]
            ],
            "layout": {
              "line-cap": "round",
              "line-join": "round"
            },
            "paint": {
              "line-color": s.strokeStyle || "#000",
              "line-width": s.lineWidth / 50 || 3
            }
          })
          break;
        default:
          layers.push({
            "id": s._id,
            "type": "fill",
            "filter": ["all", ["==", "$type", "Polygon"],
              ['==', 'active', 'false'],
              ['==', 'user_uid', s._id]
            ],
            "paint": {
              "fill-color": s.fillStyle || "#D20C0C",
              "fill-outline-color": s.strokeStyle || "#D20C0C",
              "fill-opacity": 0.1
            }
          })
          layers.push({
            "id": s._id + "-stroke-line",
            "type": "line",
            "filter": ["all", ["==", "$type", "Polygon"],
              ['==', 'active', 'false'],
              ['==', 'user_uid', s._id]
            ],
            "layout": {
              "line-cap": "round",
              "line-join": "round"
            },
            "paint": {
              "line-color": s.strokeStyle || "#D20C0C",
              "line-width": s.lineWidth / 50 || 3,
              "line-dasharray": [0.1, 2]
            }
          })
      }
    })


    /*自定义扩展*/
    const modes = MapBoxDraw.modes;
    modes.draw_freePolygon = freePolygon;//自由面
    modes.draw_Rectangle = Rectangle;//矩形
    modes.draw_mulpnts = LotsOfPointsMode;//自定义多点
    modes.draw_straightArrow = DrawStraightArrow;//自定义直箭头
    modes.draw_DiagonalArrow = DrawDiagonalArrow;//斜直箭头
    modes.draw_DoveTailStraightArrow = DrawDoveTailStraightArrow;//燕尾直箭头
    modes.draw_DoveTailDiagonalArrow = DrawDoveTailDiagonalArrow;//燕尾斜箭头
    modes.draw_DoubleArrow = DrawDoubleArrow;//双箭头
    //modes.draw_CutLineMode = CutLineMode

    this._drawControl = new MapBoxDraw({
      displayControlsDefault: false,
      defaultMode: 'simple_select',
      controls: {
        modes: modes,
        trash: true
      }, //显示默认的删除的按钮
      styles: this.drawControlStyles.concat(layers),
      userProperties: true //用户自定标签
    })
    this.getMap().addControl(this._drawControl);
    return this._drawControl;
  }


  /**
 * 添加Marker
 * @param {*} latlng 
 */
  addMarker(latlng) {
    this.tempMarker.remove();
    this.tempMarker.setLngLat(latlng).addTo(this.getMap());
  }
  /**
   * 删除Marker
   */
  removeMarker() {
    this.tempMarker.remove();
  }

  /**
   * 更改模式
   * @param mode
   */
  setChangeMode(mode, selectId) {
    if (this._drawControl) {
      this._drawControl.changeMode(mode, selectId);
    }

  }


  /**
   * 设置符号库
   * @param symbol
   */
  setSelectSymbol(symbol) {
    this.selectSymbol = symbol;
  }

  /**
   * 获取drawControl
   * @returns {*|MapBoxDraw}
   */
  getDrawControl() {
    return this._drawControl;
  }


  /**
 * 设置数据
 * @param {数据源名称} dsName 
 * @param {*} fc 
 */
  setData(dsName, fc) {
    if (!this.getMap().getSource(dsName)) {
      return;
    }
    this.getMap().getSource(dsName).setData(fc);
  }


  /**
   * 获取标绘内容
   */
  getDrawControlFC() {
    if (this._drawControl) {
      return this._drawControl.getAll();
    }
    return undefined;

  }
  /**
   * 设置标绘内容
   * @param {*} fc 
   */
  setDrawControlFC(fc) {
    if (this._drawControl) {
      this._drawControl.set(fc);
    }
  }
  /**
   *  设置边界
   * @param {*} bounds 
   * @param {*} padding 
   */
  setBounds(bounds, padding) {
    this.getMap().fitBounds(bounds, { padding: padding });
  }









  /**
  * 清除遥感数据
  */
  clearRemoteImageLayers() {
    for (let i = 0; i < this._remoteImages.length; i++) {
      let layer = this._remoteImages[i];
      const l = layer.param ? layer.param.layers ? layer.param.layers[0] : undefined : undefined;
      this.removeLayer(l ? l.source : undefined);
    }
  }

  /**
  * 添加遥感影像图层
  * @param layers
  */
  leftRemoteImageLayers(layers, beforeID) {
    //先清除图层
    //再添加图层
    this.clearRemoteImageLayers();
    this._remoteImages = [];
    for (let i = 0; i < layers.length; i++) {
      let layer = layers[i];
      //基础地图之上专题图层之下
      let bottomOfTopLayerId = beforeID ? beforeID : (this.drawControlStyles && this.drawControlStyles.length > 0 ? this.drawControlStyles[0].id + ".cold" : undefined);
      const isExist = this.hgcMapBoxUtil.isLayerExist(bottomOfTopLayerId)
      this.addLayer(layer, (isExist ? bottomOfTopLayerId : undefined)).then(res => {
        layer.param = { layers: res };
      });
      this._remoteImages.push(layer);
    }

  }


  rightRemoteImageLayers(layers, beforeID) {
    this.leftRemoteImageLayers(layers, beforeID)
  }


  //////////////////////////////////////






  /**
   * 属性查询
   * @param layer
   * @param startIndex
   * @param size
   * @returns {Promise<never> | Promise<any>}
   */

  async queryLayerAttribute(layer, startIndex, size, sql) {
    if (!layer) {
        return Promise.reject('图层不存在!');
    }
    const param = this._parseLayerUrlParam(layer.url);
    let realUrl = this._parseLayerQueryUrl(layer.url);
    switch (param && param.layerType) {
        case "layer_sm_vec": //超图发布的矢量瓦片服务
            //尽量使用后台配置的url和source-layer
            const sourceLayer = this.hgcMapBoxUtil.getSortFactory().getSourceLayerName(layer._id);
            let res = await SmQuery.mapServiceLayerSearchBySQL(sourceLayer, sql[0] === "" ? '1=1' : sql[1] + " LIKE '%" + sql[0] + "%'", realUrl, startIndex, size);
            return { data:res.result.recordsets.length > 0 ? res.result.recordsets[0].features.features:[], total: res.result.totalCount }
        case "layer_sm_25d": //2.5D服务

            break;
        case 'layer_sm_es': //EChart服务

            break;
        case 'layer_hgc_geojson': //接入自定义服务
            //自定义的矢量瓦片
            let res1 = await this.hgcMapBoxUtil.getSortFactory().getHgcCustomData(layer._id,undefined, { skip: startIndex, limit: size, queryField: ("properties." + sql[1]), query: sql[0] });
            return { data: res1.data.data.data, total: res1.data.data.total }
        default:
            break;
    }
}




setHightLihgtFilter(sourceID,featureID){
  this.sf.setHLFilter(sourceID, featureID)
}

  /**
   * 清除高亮
   * @param layerId
   */
  clearHightLightFilter(sourceId) {
    this.sf.setHLFilter(sourceId, "")
  }

  /**
   * 图层统计
   * @param layer
   * @param startIndex
   * @param size
   * @returns {Promise<never> | Promise<any>}
   */
  queryLayerStatics(url, name, field) {
    if (name === '') {
      return Promise.reject('图层不存在!')
    }
    return SmQuery.mapServiceLayerStaticsBySQL(url, name, field)
  }


  addSource(sourceId) {
    if (this.getMap().getSource(sourceId)) {
      return
    }
    this.getMap().addSource(sourceId, {
      type: 'geojson',
      data: { type: 'FeatureCollection', features: [] },
      lineMetrics: true
    })
  }

  addGeojsonLayer(id,geojson){
    if(this.getMap().getLayer(id)){
       return;
    }
    this.getMap().addLayer(geojson)
  }

  
 





}
